package com.letwal.cmcvnd.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.letwal.cmcvnd.R
import com.letwal.cmcvnd.base.BaseEditAction
import com.letwal.cmcvnd.base.BaseFormAction
import com.letwal.cmcvnd.databinding.ViewLoginPasswordInputBinding
import com.letwal.cmcvnd.extend.*

/**
<declare-styleable name="LoginPasswordInput">
<attr name="inputTitle" format="string" />
<attr name="inputTextColor" format="color" />
<attr name="inputHint" format="string" />
<attr name="inputDelImageRes" format="reference" />
<attr name="inputDelImageHidden" format="boolean" />
<attr name="inputPreHintHidden" format="boolean" />
</declare-styleable>
 * */
class LoginPasswordInput : RelativeLayout, BaseFormAction,
    BaseEditAction {

    lateinit var mViewBinding: ViewLoginPasswordInputBinding
    private lateinit var vRootView: View

    private var inputTextColor: Int = 0
    private var inputHintColor: Int = 0
    private var inputTitle: String? = null
    private var inputText: String? = null
    private var inputHint: String? = null
    private var inputDelImageRes: Int = 0
    private var inputDelImageHidden: Boolean = false
    private var inputPreHintHidden: Boolean = false
    private var inputPreHintImageRes: Int = 0
    private var inputIsTitleBold: Boolean = true
    private var inputTitleSize: Float = 0F

    private var mSupportFragmentManager: FragmentManager? = null

    private var mTempInputValue: String = ""
    private var mOnActionClickListener: (Int) -> Unit = {}
    private var mOnTextChangedListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.LoginPasswordInput)
                inputTextColor = array.getColor(
                    R.styleable.LoginPasswordInput_inputTextColor,
                    ContextCompat.getColor(cxt, R.color.text_title)
                )
                inputText =
                    array.getString(R.styleable.LoginPasswordInput_inputText)

                inputTitle =
                    array.getString(R.styleable.LoginPasswordInput_inputTitle)

                inputHintColor = array.getColor(
                    R.styleable.LoginPasswordInput_inputHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                inputHint =
                    array.getString(R.styleable.LoginPasswordInput_inputHint)

                inputDelImageRes =
                    array.getResourceId(
                        R.styleable.LoginPasswordInput_inputDelImageRes,
                        R.drawable.icon_input_no_eye
                    )
                inputDelImageHidden = array.getBoolean(
                    R.styleable.LoginPasswordInput_inputDelImageHidden,
                    false
                )
                inputPreHintImageRes =
                    array.getResourceId(
                        R.styleable.LoginPasswordInput_inputPreHintImageRes,
                        R.drawable.icon_login_lock
                    )

                inputIsTitleBold = array.getBoolean(
                    R.styleable.LoginPasswordInput_inputIsTitleBold,
                    true
                )

                inputTitleSize = array.getDimension(
                    R.styleable.LoginPasswordInput_inputTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_12
                    ).toFloat()
                )

                inputPreHintHidden = array.getBoolean(
                    R.styleable.LoginPasswordInput_inputPreHintHidden,
                    false
                )

                array.recycle()
            }
        }
        context?.let {
            vRootView =
                View.inflate(it, R.layout.view_login_password_input, this)
            mViewBinding =
                ViewLoginPasswordInputBinding.bind(vRootView)
            initSubviews()
        }
    }

    override fun initSubviews() {
        try {
            mViewBinding.textLoginPasswordTitle.text = inputTitle
            mViewBinding.textLoginPasswordTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                inputTitleSize
            )
            if (inputIsTitleBold) {
                mViewBinding.textLoginPasswordTitle.addBoldStyle()
            } else {
                mViewBinding.textLoginPasswordTitle.addNormalStyle()
            }

            mViewBinding.editLoginPassword.setText(inputText)
            mViewBinding.editLoginPassword.setTextColor(inputTextColor)

            mViewBinding.editLoginPassword.hint = (inputHint)
            mViewBinding.editLoginPassword.setHintTextColor(inputHintColor)

            mViewBinding.imageLoginPasswordDel.setImageResource(inputDelImageRes)

            mViewBinding.llLoginPasswordDelBg.setOnClickListener {
                mOnActionClickListener.invoke(0)
            }

            mViewBinding.imageLoginPasswordDel.setOnClickListener {
                mOnActionClickListener.invoke(0)
            }

            if (inputPreHintHidden) {
                mViewBinding.imageLoginPasswordPreHint.visibility = GONE
            } else {
                mViewBinding.imageLoginPasswordPreHint.visibility = VISIBLE
            }


            mViewBinding.editLoginPassword.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isCompleted()
                    val gContent = getContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mTempInputValue,
                                false
                            )
                        ) {
                            try {
                                mTempInputValue = gContent
                                recordInputEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                    val tempContent = getContent()
                    if (tempContent.isNotBlank()) {
                        if (inputDelImageHidden) {
                            mViewBinding.llLoginPasswordDelBg.visibility = GONE
                        } else {
                            mViewBinding.llLoginPasswordDelBg.visibility =
                                VISIBLE
                        }

                    } else {
                        mViewBinding.llLoginPasswordDelBg.visibility = GONE
                    }
                }
            }
            mViewBinding.editLoginPassword.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getContent()
                    if (tempContent.isNotBlank()) {
                        if (inputDelImageHidden) {
                            mViewBinding.llLoginPasswordDelBg.visibility = GONE
                        } else {
                            mViewBinding.llLoginPasswordDelBg.visibility =
                                VISIBLE
                        }
                    } else {
                        mViewBinding.llLoginPasswordDelBg.visibility = GONE
                    }
                    //回调
                    mOnTextChangedListener.invoke(
                        tempContent
                    )
                }
            })

            mViewBinding.llLoginPasswordDelBg.setOnClickListener {
                mViewBinding.editLoginPassword.setText("")
            }
            mViewBinding.imageLoginPasswordDel.setOnClickListener {
                mViewBinding.editLoginPassword.setText("")
            }

            //增加星号显示
            mViewBinding.textLoginPasswordTitle.addHighlightStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

            //显示与隐藏密码
            mViewBinding.imageLoginPasswordDel.setOnClickListener {
                val iTag = mViewBinding.imageLoginPasswordDel.tag as String
                val eText = mViewBinding.editLoginPassword.text.toString().trim()
                if (iTag.equals("close", true)) {
                    mViewBinding.editLoginPassword.transformationMethod =
                        (HideReturnsTransformationMethod.getInstance())

                    mViewBinding.imageLoginPasswordDel.tag = "open"
                    mViewBinding.editLoginPassword.setSelection(eText.length)
                    mViewBinding.imageLoginPasswordDel.setImageResource(R.drawable.icon_input_eye)

                } else {
                    mViewBinding.editLoginPassword.transformationMethod =
                        (PasswordTransformationMethod.getInstance())

                    mViewBinding.imageLoginPasswordDel.tag = "close"
                    mViewBinding.editLoginPassword.setSelection(eText.length)
                    mViewBinding.imageLoginPasswordDel.setImageResource(R.drawable.icon_input_no_eye)
                }
            }

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setContent(content: String) {
        mViewBinding.editLoginPassword.setText(content)
    }

    fun getContent(): String {
        return mViewBinding.editLoginPassword.text.toString().trim().replace(" ", "")
    }

    fun isCompleted(): Boolean {
        val gcontent = getContent()
        if (gcontent.isBlank()) {
            mViewBinding.rlLoginPasswordBg.setBackgroundResource(R.drawable.form_input_error)
            mViewBinding.textLoginPasswordErrTip.visibility = VISIBLE
            return false
        }

        mViewBinding.textLoginPasswordErrTip.visibility = GONE
        mViewBinding.rlLoginPasswordBg.setBackgroundResource(R.drawable.form_input)
        return true
    }

    fun isCompletedSlient(): Boolean {
        val gcontent = getContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toBeFocusPointAndShowInputKeyboard() {
        try {
            mViewBinding.editLoginPassword.isFocusable = true
            mViewBinding.editLoginPassword.isFocusableInTouchMode = true
            mViewBinding.editLoginPassword.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(
                            mViewBinding.editLoginPassword,
                            0
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toBeFocusPoint() {
        try {
            mViewBinding.editLoginPassword.isFocusable = true
            mViewBinding.editLoginPassword.isFocusableInTouchMode = true
            mViewBinding.editLoginPassword.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setInputHint(hint: String) {
        val hintFormat = hint.toPhoneNumberInputHint()
        mViewBinding.editLoginPassword.hint = hintFormat
    }

    override fun setFragmentManager(manager: FragmentManager) {
        mSupportFragmentManager = manager
    }

    override fun setOnActionClickListener(listener: (Int) -> Unit) {
        mOnActionClickListener = listener
    }

    override fun setOnTextChangedListener(listener: (String) -> Unit) {
        mOnTextChangedListener = listener
    }

    override fun setTitle(title: String) {

    }

    override fun setDetail(detail: String) {

    }

    override fun setHint(hint: String) {
        setInputHint(hint)
    }

    override fun setDetailColor(detailColor: Int) {

    }

    override fun setTitleColor(titleColor: Int) {

    }

    fun clean() {
        mViewBinding.editLoginPassword.setText(null)
    }

}